<template>
  <!-- 员工管理 -->
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="success" :disabled="checkPermission('employees-export')" @click="exportsimple">简单表头导出</el-button>
          <el-button size="small" type="warning" :disabled="checkPermission('employees-export')" @click="exportMutil">复杂表头导出</el-button>
          <el-button size="small" type="danger" :disabled="checkPermission('employees-import')" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button size="small" type="primary" :disabled="checkPermission('employees-add')" @click="addUser">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatter"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="{row}">
              <el-switch
                :value="row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push(`/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="delUser(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :total="total"
            :current-page="page.page"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <add-employee ref="addUser" />
  </div>
</template>

<script>
import { getUserInfoList, delUserInfo } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
export default {
  components: {
    AddEmployee // 弹出层组件
  },
  data() {
    return {
      page: {
        // 员工列表请求条数及页面
        page: 1,
        size: 5
      },
      list: [], // 员工列表
      total: 0, // 员工总数量
      showDialog: false // 弹出层控制
    }
  },
  created() {
    this.getUserInfoList()
  },
  methods: {
    // 获取员工列表
    async getUserInfoList() {
      const { total, rows } = await getUserInfoList(this.page)
      this.list = rows
      this.total = total
    },
    // 改变分页条数
    changePage(type) {
      this.page.page = type
      this.getUserInfoList() // 调用接口 刷新数据
    },
    // 格式化内容
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async delUser(id) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        try {
          await delUserInfo(id)
          if (this.list.length === 1 && this.page.page > 1) {
            this.page.page--
          }
          this.getUserInfoList() // 调用接口，更新数据
          this.$message.success('删除员工成功')
        } catch (error) {
          console.log(error.message)
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 新增员工(打开弹窗)
    addUser() {
      this.$refs.addUser.dialogVisible = true
    },
    // 简单表头导出
    async exportsimple() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 请求员工列表数据，拿到员工数据
      const { rows } = await getUserInfoList({ pahe: 1, size: this.total })
      // 处理员工列表数据，拿到excel所需要的数据
      const data = rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          }
          // 处理聘用形式
          if (headers[key] === 'formOfEmployment') {
            return this.formatter('', '', item[headers[key]])
          }
          return item[headers[key]]
        })
      })
      const tHeader = Object.keys(headers)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          filename: '员工简单列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 复杂表头导出
    async exportMutil() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // 请求员工列表数据，拿到员工数据
      const { rows } = await getUserInfoList({ pahe: 1, size: this.total })
      // 处理员工列表数据，拿到excel所需要的数据
      const data = rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          }
          // 处理聘用形式
          if (headers[key] === 'formOfEmployment') {
            return this.formatter('', '', item[headers[key]])
          }
          return item[headers[key]]
        })
      })
      const tHeader = Object.keys(headers)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          multiHeader,
          merges,
          filename: '员工简单列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    }
  }
}
</script>

<style></style>
